
Imports System
Imports System.IO
Imports System.Text
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports _2bMatesSite.BO
Imports _2bMatesSite.Controls

Namespace _2bMatesSite
	''' <summary>
	''' Summary description for my_groups.
	''' </summary>
	Public Partial Class my_groups
		Inherits BaseWebPage
		Protected lbDeleteGroup As System.Web.UI.WebControls.LinkButton
		Protected lbUnsubscribeGroup As System.Web.UI.WebControls.LinkButton
		Protected lblMember As System.Web.UI.WebControls.Label

		Protected blankImagesCount As Integer = 0
		Protected currentPageNumber As Integer = 0
		Protected firstPageNumber As Integer = 0
		' the first page of page links
		Protected lastPageNumber As Integer = 0
		Protected pagesRest As Integer = 0
		Public action As String = "0"
		Protected sSortBy As String = Constants.GROUP_SORT_BY_MOST_RECENT
		Protected myGroups As New ArrayList()
		Private usr As User = Nothing

		Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
			' this.pageTemplate.PageTitle = PageTitles.MY_GROUPS_PAGE;

			usr = LoggedUser
			If usr = Nothing Then
				Common.Utils.RedirectToLoginPage(Page)
			End If

			Me.initPageTitles(Constants.MY_GROUPS, "", Form1, Nothing, Nothing)
			Me.initAdvertisements(Form1, Nothing)

			' init tabs
			ucGroupTabs.ActiveTab = 3
			ucGroupTabs.PageName = Constants.MY_GROUPS

			' init user whose friends to see: a member ot logged user
			dlAllGroups.RepeatColumns = Constants.MAX_PICTURES_ON_ROW

			'init sort by param
			If Request.Params(Constants.GROUP_SORT_BY_PARAM) <> Nothing AndAlso Request.Params(Constants.GROUP_SORT_BY_PARAM) <> "" Then
				sSortBy = Request.Params(Constants.GROUP_SORT_BY_PARAM)
			End If

			' check if the value is valid, if not - init woth default value: Most Recent
			If sSortBy <> Constants.GROUP_SORT_BY_MOST_RECENT AndAlso sSortBy <> Constants.GROUP_SORT_BY_NAME AndAlso sSortBy <> Constants.GROUP_SORT_BY_POPULARITY Then
				sSortBy = Constants.GROUP_SORT_BY_MOST_RECENT
			End If


			'			// set add/edit friends visiblity
			'			if(usrID != LoggedUser.ID) // if member
			'			{
			'				imgAddFriends.Visible = false;
			'				lbJoin.Visible = false;
			'				imgEditFriends.Visible = false;
			'				lbEditGroups.Visible = false;
			'			}

			' init my groups array
			myGroups = Groups.MyGroups(usr.ID, sSortBy)
			Dim GroupsCount As Double = myGroups.Count
			litGroupsCount.Text = GroupsCount.ToString()
			If GroupsCount = 0 Then
				tblGroups.Visible = False
				imgEditFriends.Visible = False
				lbEditGroups.Visible = False
				lblNoGroups.Visible = True
			Else
				' init SortBy Links visibility, when sort functionality is added
				Select Case sSortBy
					Case Constants.GROUP_SORT_BY_POPULARITY
						lbMostRecent.Visible = True
						lblMostRecent.Visible = False
						lbPopularity.Visible = False
						lblPopularity.Visible = True
						lbName.Visible = True
						lblName.Visible = False
						Exit Select
					Case Constants.GROUP_SORT_BY_NAME
						lbMostRecent.Visible = True
						lblMostRecent.Visible = False
						lbPopularity.Visible = True
						lblPopularity.Visible = False
						lbName.Visible = False
						lblName.Visible = True
						Exit Select
					Case Constants.GROUP_SORT_BY_MOST_RECENT
						lbMostRecent.Visible = False
						lblMostRecent.Visible = True
						lbPopularity.Visible = True
						lblPopularity.Visible = False
						lbName.Visible = True
						lblName.Visible = False
						Exit Select
				End Select

				' init Pagers
				dgPager.RedirectPage = String.Format("{0}?{1}={2}", Constants.MY_GROUPS, Constants.GROUP_SORT_BY_PARAM, sSortBy)
				dgPager.MaxPageNumber = Convert.ToInt32(Math.Ceiling(GroupsCount / Constants.MAX_PICTURES_ON_PAGE))
				dgPagerUp.RedirectPage = String.Format("{0}?{1}={2}", Constants.MY_GROUPS, Constants.GROUP_SORT_BY_PARAM, sSortBy)
				dgPagerUp.MaxPageNumber = Convert.ToInt32(Math.Ceiling(GroupsCount / Constants.MAX_PICTURES_ON_PAGE))
				action = Request.Params("action")
				dgPager.Action = action
				dgPagerUp.Action = action
				If action = Constants.SEE_ALL_FRIENDS_EDIT_ACTION Then
					imgEditFriends.Visible = False
					lbEditGroups.Visible = False
				End If

				' initialize listing literals

				dgPager.dgListing.TotalCount = Convert.ToInt32(GroupsCount)
				dgPagerUp.dgListing.TotalCount = Convert.ToInt32(GroupsCount)
				'dgListingUp.TotalCount = Convert.ToInt32(GroupsCount);

				'initialize current page number
				If Convert.ToInt32(Request.Params("page")) = 0 OrElse dgPager.CurrentPageNumber = 1 Then
					dgPager.CurrentPageNumber = 1
					dgPagerUp.CurrentPageNumber = 1
					txtStartIndexHidden.Text = "0"
				Else
					dgPager.CurrentPageNumber = Convert.ToInt32(Request.Params("page"))
					dgPagerUp.CurrentPageNumber = Convert.ToInt32(Request.Params("page"))
					txtStartIndexHidden.Text = Convert.ToString(((dgPager.CurrentPageNumber - 1) * Constants.MAX_PICTURES_ON_PAGE))
				End If

				dgPager.PagesRest = dgPager.MaxPageNumber - dgPager.FirstPageNumber + 1
				dgPager.LastPageNumber = Math.Min(dgPager.PagesRest, Constants.MAX_PAGES_NUMS_ON_PAGE)
				dgPagerUp.PagesRest = dgPagerUp.MaxPageNumber - dgPagerUp.FirstPageNumber + 1
				dgPagerUp.LastPageNumber = Math.Min(dgPagerUp.PagesRest, Constants.MAX_PAGES_NUMS_ON_PAGE)
				If Not IsPostBack Then
					BindList()
				End If
			End If
		End Sub

		Public Function CreateDataSource() As ICollection
			Dim startIndex As Integer = Convert.ToInt32(txtStartIndexHidden.Text)
			Dim endIndex As Integer = startIndex + Constants.MAX_PICTURES_ON_PAGE
			Dim i As Integer
			Dim dt As New DataTable()
			Dim dr As DataRow

			dt.Columns.Add(New DataColumn("ImageURL", GetType(String)))
			dt.Columns.Add(New DataColumn("Name", GetType(String)))
			dt.Columns.Add(New DataColumn("DelGroupVisibility", GetType(Boolean)))
			dt.Columns.Add(New DataColumn("GroupID", GetType(String)))
			dt.Columns.Add(New DataColumn("Moderator", GetType(String)))
			dt.Columns.Add(New DataColumn("FullName", GetType(String)))
			dt.Columns.Add(New DataColumn("UnsubscribeGroupVisibility", GetType(Boolean)))
			Dim temp As GroupPicture
			Dim GroupsCount As Integer = myGroups.Count
			Dim imagesOnLastRow As Integer = 0
			Dim t As Integer = 0
			Dim counter As Integer = 0

			txtGroupsCountHidden.Text = GroupsCount.ToString()
			endIndex = Math.Min(endIndex, GroupsCount)
			t = (endIndex - startIndex)
			Math.DivRem(t, Constants.MAX_PICTURES_ON_ROW, imagesOnLastRow)
			dgPager.dgListing.StartIndex = startIndex + 1
			dgPager.dgListing.EndIndex = endIndex
			dgPagerUp.dgListing.StartIndex = startIndex + 1
			dgPagerUp.dgListing.EndIndex = endIndex

			counter = 0
			i = 0

			For Each grp As BO.Group In myGroups
				If counter >= startIndex AndAlso counter < endIndex Then
					dr = dt.NewRow()
					temp = grp.DefaultPicture

					If temp <> Nothing Then
						dr(0) = Pictures.GetPictureSrcFullURL(temp, True, "../")
					Else
						dr(0) = "../images/default_thumbnail.gif"
					End If
					dr(1) = getBeginning(HttpUtility.HtmlEncode(grp.Name), Constants.MAX_NAME_LENGTH_ABOVE_IMAGE)
					If action = Constants.SEE_ALL_FRIENDS_EDIT_ACTION Then
						If grp.Uid = usr.ID Then
							dr(2) = True
							dr(6) = False
						Else
							dr(2) = False
							dr(6) = True
						End If
					Else
						dr(2) = False
						dr(6) = False
					End If
					dr(3) = grp.ID
					If grp.Uid = usr.ID Then
						dr(4) = "Moderator"
					End If
					dr(5) = grp.Name
					dt.Rows.Add(dr)
					System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
				End If
				System.Math.Max(System.Threading.Interlocked.Increment(counter),counter - 1)
			Next

			If imagesOnLastRow <> 0 Then
				blankImagesCount = Constants.MAX_PICTURES_ON_ROW - imagesOnLastRow
				i = imagesOnLastRow
				While i < Constants.MAX_PICTURES_ON_ROW
					dr = dt.NewRow()
					'dr[0] = "../images/empty_image.gif";
					dr(0) = "../images/spacer.gif"
					dr(1) = ""
					dr(2) = "false"
					dr(6) = "false"
					dt.Rows.Add(dr)
					System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
				End While
			End If

			Dim dv As New DataView(dt)
			Return dv
		End Function

		Public Sub BindList()
			dlAllGroups.DataSource = CreateDataSource()
			dlAllGroups.DataBind()

			Dim itemsCount As Integer = dlAllGroups.Items.Count
			Dim blankImageIndex As Integer = itemsCount - blankImagesCount
			Dim i As Integer = 0
			i = blankImageIndex
			While i < itemsCount
				(DirectCast(dlAllGroups.Items(i).FindControl("lbName"), System.Web.UI.WebControls.LinkButton)).CssClass = "empty_image"
				(DirectCast(dlAllGroups.Items(i).FindControl("imgPhoto"), System.Web.UI.WebControls.ImageButton)).CssClass = "empty_image"
				System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
			End While
		End Sub

		Protected Overloads Overrides Sub Render(ByVal writer As HtmlTextWriter)
			Dim stringBuilder As New StringBuilder()
			Dim stringWriter As New StringWriter(stringBuilder)
			Dim htmlWriter As New HtmlTextWriter(stringWriter)
			MyBase.Render(htmlWriter)
			Dim html As String = stringBuilder.ToString()
			Dim start As Integer = html.IndexOf("<form name=""") + 12
			Dim [end] As Integer = html.IndexOf("""", start)
			Dim formID As String = html.Substring(start, [end] - start)
			Dim replace As String = formID.Replace(":", "_")
			html = html.Replace("document." + formID, "document." + replace)
			writer.Write(html)
		End Sub

		#region Web Form Designer generated code
		Protected Overloads Overrides Sub OnInit(ByVal e As EventArgs)
			'
			' CODEGEN: This call is required by the ASP.NET Web Form Designer.
			'
			InitializeComponent()
			MyBase.OnInit(e)
		End Sub

		''' <summary>
		''' Required method for Designer support - do not modify
		''' the contents of this method with the code editor.
		''' </summary>
		Private Sub InitializeComponent()
			AddHandler Me.dlAllGroups.ItemCommand, AddressOf Me.dlAllGroups_ItemCommand

		End Sub
#End Region

		Private Sub dlAllGroups_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs)
			Dim src As Object = e.CommandSource
			Dim srcType As String = src.[GetType]().ToString()
			Dim cmd As String = e.CommandName
			Dim arg As String = ""

			If srcType.Equals("System.Web.UI.WebControls.ImageButton") Then
				arg = (DirectCast(src, ImageButton)).CommandArgument
			Else
				arg = (DirectCast(src, LinkButton)).CommandArgument
			End If

			Select Case cmd
				Case "Delete"
					Response.Redirect(Constants.CANCEL_ACCOUNT + "?" + Constants.GROUP_PARAM + "=" + e.CommandArgument + "&" + Constants.PAGE_FROM + "=" + Constants.MY_GROUPS)
					Exit Select
				Case "Unsubscribe"
					Response.Redirect(Constants.CONFIRM_UNSUBSCRIBE + "?" + Constants.GROUP_PARAM + "=" + e.CommandArgument)
					Exit Select
				Case "MemberRedirect"
					Response.Redirect(Constants.GROUP_WELCOME + "?" + Constants.GROUP_PARAM + "=" + e.CommandArgument)
					Exit Select
			End Select
		End Sub

		Protected Sub lbEditGroups_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.MY_GROUPS + "?action=" + Constants.SEE_ALL_FRIENDS_EDIT_ACTION)
		End Sub

		Protected Sub lbJoin_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.CREATE_GROUP)
		End Sub

		Protected Sub lbMostRecent_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.MY_GROUPS + "?" + Constants.GROUP_SORT_BY_PARAM + "=" + Constants.GROUP_SORT_BY_MOST_RECENT)
		End Sub

		Protected Sub lbPopularity_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.MY_GROUPS + "?" + Constants.GROUP_SORT_BY_PARAM + "=" + Constants.GROUP_SORT_BY_POPULARITY)
		End Sub

		Protected Sub lbName_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.MY_GROUPS + "?" + Constants.GROUP_SORT_BY_PARAM + "=" + Constants.GROUP_SORT_BY_NAME)
		End Sub

		====================
		' This public property was added by conversion wizard to allow the access of a protected, autogenerated member variable Form1.
		====================
		Public ReadOnly Property Form1() As System.Web.UI.HtmlControls.HtmlForm
			Get
				Return Migrated_Form1
			End Get
		End Property
		'set { Migrated_Form1 = value; }
	End Class
End Namespace






